/*
 * Name: Minh-Tuan ta
 * Class: Register.java
 */

package actions;

import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import data.UserDB;
import beans.*;

public class Register extends Action {
	

	@Override
	protected String doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		return "/WEB-INF/views/content/Register.jsp";
	}

	@Override
	protected String doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String url = "Register";
		HttpSession session = request.getSession();
		
		User user = new User();
		
		user.setAddress1(request.getParameter("address1"));
		user.setAddress2(request.getParameter("address2"));
		user.setCity(request.getParameter("city"));
		String year = request.getParameter("dobYear");   //This needs to stay string - Myles
		String month = request.getParameter("dobMonth"); //This needs to stay string - Myles
		String day = request.getParameter("dobDay");     //This needs to stay string - Myles
		java.sql.Date date = java.sql.Date.valueOf(year + "-" + month + "-" + day);
		user.setDob(date);
		user.setEmail(request.getParameter("email"));
		user.setFirstName(request.getParameter("firstName"));
		user.setGender(Boolean.parseBoolean(request.getParameter("gender")));
		user.setLastlogin(new Timestamp(new java.util.Date().getTime()));
		user.setLastName(request.getParameter("lastName"));
		user.setPassword(request.getParameter("password"));
		user.setPhone(request.getParameter("phone"));
		user.setPicturePath("images/no-avatar.jpg");
		user.setState(request.getParameter("state"));
		user.setUserName(request.getParameter("userName"));
		user.setZip(request.getParameter("zip"));
		
		if (UserDB.addUser(user) == 1) //add successfully
		{
			//redirect user to the last url or to the home page
			url = getLastURL(request, session);
			
			//log the user in
			session.setAttribute("User", UserDB.getUser(user.getUserName()));
			
		}
		else
		{
			url = "Register";
			session.setAttribute("RegisterStatus", "Can't register");
		}
		
		return url;
	}

	@Override
	protected void setURLMapping() {
		// TODO Auto-generated method stub
		this.urlMapping = "/Register";
	}

	@Override
	protected void setupPage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setAttribute("pageTitle", "Register");
	}

}
